<template>
  <div class="chat-container">
    <div class="chat-header">
      <div class="header-title">
        <i class="el-icon-service"></i>
        <span>在线客服</span>
      </div>
      <div class="connection-status" :class="{ 'connected': isConnected }">
        <i class="el-icon-circle-check" v-if="isConnected"></i>
        <i class="el-icon-circle-close" v-else></i>
        {{ isConnected ? '已连接' : '未连接' }}
      </div>
    </div>
    <div class="chat-box" ref="chatBox">
      <div class="chat-date">{{ currentDate }}</div>
      <div v-for="(msg, index) in messages" 
           :key="index" 
           :class="{'my-message': msg.sender === userId, 'other-message': msg.sender !== userId}">
        <div class="message-wrapper">
          <div class="avatar" :class="{'my-avatar': msg.sender === userId}">
            {{ msg.sender === userId ? '我' : '客服' }}
          </div>
          <div class="message-content">
            <div class="message-bubble">
              {{ msg.content }}
            </div>
            <div class="message-time">{{ getCurrentTime() }}</div>
          </div>
        </div>
      </div>
    </div>
    <div class="chat-input">
      <input 
        v-model="message" 
        @keyup.enter="sendMessage" 
        placeholder="输入消息按回车发送..." 
      />
      <el-button 
        type="primary" 
        icon="el-icon-s-promotion" 
        :disabled="!message.trim()"
        @click="sendMessage">
        发送
      </el-button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      socket: null,
      messages: [],
      message: "",
      userId: localStorage.getItem("userId") || "user123",
      platformId: "platform",
      isConnected: false,
      currentDate: new Date().toLocaleDateString()
    };
  },
  mounted() {
    this.socket = new WebSocket("ws://localhost:9081/websocket");

    this.socket.onopen = () => {
      console.log("WebSocket 连接成功");
      this.isConnected = true;
      this.socket.send(JSON.stringify({ type: "register", sender: this.userId }));
    };

    this.socket.onmessage = (event) => {
      try {
        let msg = event.data;
        if (typeof msg === 'string') {
          try {
            msg = JSON.parse(msg);
          } catch (e) {
            const [sender, content] = msg.split(': ');
            msg = {
              type: 'chat',
              sender: sender,
              content: content || msg
            };
          }
        }
        this.messages.push(msg);
        this.scrollToBottom();
      } catch (error) {
        console.error('消息处理错误：', error);
        this.messages.push({
          type: 'system',
          sender: 'System',
          content: event.data
        });
      }
    };

    this.socket.onerror = (error) => {
      console.error('WebSocket 错误：', error);
      this.isConnected = false;
      this.$message.error('连接发生错误');
    };

    this.socket.onclose = () => {
      console.log('WebSocket 连接关闭');
      this.isConnected = false;
      this.$message.warning('连接已关闭');
    };
  },
  methods: {
    sendMessage() {
      if (this.message.trim() === "") return;

      const chatMessage = {
        type: "chat",
        sender: this.userId,
        receiver: this.platformId,
        content: this.message
      };

      try {
        this.socket.send(JSON.stringify(chatMessage));
        // 将消息添加到本地消息列表
        this.messages.push(chatMessage);
        this.message = "";
        this.scrollToBottom();
      } catch (error) {
        console.error('发送消息失败：', error);
        this.$message.error('发送失败，请重试');
      }
    },
    getCurrentTime() {
      const now = new Date();
      return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const chatBox = this.$refs.chatBox;
        chatBox.scrollTop = chatBox.scrollHeight;
      });
    }
  }
};
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 60px);
  max-width: 900px;
  margin: 30px auto;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: linear-gradient(135deg, #409EFF, #36D1DC);
  color: white;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 18px;
  font-weight: 500;
}

.header-title i {
  font-size: 24px;
}

.connection-status {
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 13px;
  background: rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
}

.connection-status.connected {
  background: rgba(103, 194, 58, 0.9);
}

.chat-box {
  flex-grow: 1;
  overflow-y: auto;
  padding: 24px;
  background: #f8f9fa;
  scrollbar-width: thin;
  scrollbar-color: #ddd transparent;
}

.chat-box::-webkit-scrollbar {
  width: 5px;
}

.chat-box::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 3px;
}

.chat-box::-webkit-scrollbar-track {
  background: transparent;
}

.chat-date {
  text-align: center;
  margin: 20px 0;
  color: #909399;
  font-size: 13px;
  position: relative;
}

.chat-date::before,
.chat-date::after {
  content: '';
  position: absolute;
  top: 50%;
  width: 100px;
  height: 1px;
  background: #e4e7ed;
}

.chat-date::before {
  right: calc(50% + 50px);
}

.chat-date::after {
  left: calc(50% + 50px);
}

.message-wrapper {
  display: flex;
  align-items: flex-start;
  margin: 20px 0;
  animation: fadeIn 0.3s ease;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  color: white;
  flex-shrink: 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.my-avatar {
  background: linear-gradient(135deg, #409EFF, #36D1DC);
}

.other-message .avatar {
  background: linear-gradient(135deg, #67C23A, #95D475);
}

.message-content {
  margin: 0 12px;
  max-width: 70%;
}

.message-bubble {
  padding: 12px 18px;
  border-radius: 18px;
  font-size: 14px;
  line-height: 1.6;
  position: relative;
  word-break: break-word;
}

.my-message .message-wrapper {
  flex-direction: row-reverse;
}

.my-message .message-content {
  align-items: flex-end;
}

.my-message .message-bubble {
  background: linear-gradient(135deg, #409EFF, #36D1DC);
  color: white;
  border-bottom-right-radius: 4px;
  margin-right: 8px;
}

.other-message .message-bubble {
  background: white;
  color: #303133;
  border-bottom-left-radius: 4px;
  margin-left: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.message-time {
  font-size: 12px;
  color: #909399;
  margin-top: 6px;
  opacity: 0.8;
}

.my-message .message-time {
  text-align: right;
}

.chat-input {
  padding: 20px;
  background: white;
  border-top: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  gap: 12px;
}

input {
  flex: 1;
  padding: 12px 20px;
  border: 2px solid #ebeef5;
  border-radius: 24px;
  font-size: 14px;
  transition: all 0.3s ease;
  outline: none;
  background: #f8f9fa;
}

input:focus {
  border-color: #409EFF;
  background: white;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1);
}

input::placeholder {
  color: #909399;
}

.el-button {
  border-radius: 20px;
  padding: 12px 24px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.el-button:not(:disabled):hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 添加响应式设计 */
@media screen and (max-width: 768px) {
  .chat-container {
    margin: 0;
    height: 100vh;
    border-radius: 0;
  }

  .message-content {
    max-width: 85%;
  }
}
</style>